
import 'package:fast_contacts/fast_contacts.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/device/contact_model.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'settings_sos_state.dart';

class SettingsSosLogic extends BaseController {
  final SettingsSosState state = SettingsSosState();
  static const methodSyncSosCallInfo = "syncSosCallInfo";
  static const keySosName = "sosName";
  static const keySosPhoneNumber = "sosPhoneNumber";

  Future<List<ContactModel>> fetchContacts() async {
    List<ContactModel> contactList = <ContactModel>[];
    Map<String, ContactModel> contactMap = {};
    List<ContactField> fields = ContactField.values.toList();
    try {
      List<Contact> contacts = await FastContacts.getAllContacts(fields: fields);

      for (var contact in contacts) {
        if (contact.displayName.isEmpty) {
          continue;
        }

        var py = PinyinHelper.getShortPinyin(contact.displayName);
        if (py.isEmpty) {
          py = "#";
        }

        var initial = py.substring(0, 1).toUpperCase();
        ContactModel model;
        if (contactMap.keys.contains(initial)) {
          model = contactMap[initial]!;
        }
        else {
          model = ContactModel(section: initial, contacts: []);
          contactMap[initial] = model;
          contactList.add(model);
        }

        for (var phone in contact.phones) {
          var contactItem = ContactItem(contact.displayName, phone.number.removeAllWhitespace.trim());
          model.getContacts.add(contactItem);
        }
      }
    } on PlatformException catch (e) {
      logger.d(e);
    } finally {
    }

    contactList.sort((a, b) => a.compareTo(b));

    return contactList;
  }

  Future<void> toContactPage() async {
    var hasPermission = await Permission.contacts.isGranted;
    if (!hasPermission) {
      Permission.contacts.request().then((value) => {
        if (value.isGranted) {
          Get.toNamed("/device/settings/select_contacts")
        }
      });
    }
    else {
      Get.toNamed("/device/settings/select_contacts");
    }
  }

  void syncSosCallInfo(String name, String phoneNumber, bool goBack) {
    showLoading();
    var syncList = [];
    if (phoneNumber.isNotEmpty) {
      syncList.add({UTEPedConst.keyName: name, "phone": phoneNumber});
    }
    bRemoteReqAsync(methodSyncSosCallInfo, {
      UTEPedConst.typeList: syncList
    }).then((success) => {
      _onSyncSosCallInfo(success, name, phoneNumber, goBack),
    });
  }

  void _onSyncSosCallInfo(success, name, phoneNumber, goBack) {
    cancelLoading();

    if (success) {
      state.name = name;
      state.phone = phoneNumber;
      save(keySosName, name);
      save(keySosPhoneNumber, phoneNumber);
      if (goBack) {
        Get.offAndToNamed("/device/settings/sos");
      }

      if (phoneNumber != null && phoneNumber.toString().isNotEmpty) {
        showInfoDialog(LocaleKeys.response_success.ts, callback: ()=> {
        Get.offAndToNamed("/device/settings/sos")
        });
      }
      else {
        showInfoDialog(LocaleKeys.sos_number_del_success.ts);
      }
    }

    update(["sos_body", "delete_button"]);
  }

  onContactCheck(ContactItem contact, bool? value) {
    state.currentItem?.imported = false;
    state.currentItem = contact;
    contact.imported = value;
    state.contactItemChecked = value == true;
    update(["list_view", "save_button"]);
  }

  void onSave() {
    syncSosCallInfo(state.currentItem!.name, state.currentItem!.phone, false);
  }

  @override
  Future<void> onReady() async {
    var hasPermission = await Permission.contacts.isGranted;
    if (!hasPermission) {
      Permission.contacts.request().then((value) => {
        if (!value.isGranted) {
          showPermissionDialog(LocaleKeys.contact_permission_tips.ts)
        }
      });
    }
    super.onReady();
  }
  @override
  String getRemotePath() {
    return UTEPedConst.pathContact;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void initState() {
    state.name = read(keySosName);
    state.phone = read(keySosPhoneNumber);
  }

  @override
  void onRemoteEvent(event, method) {

  }

  onSosCheck(bool? value) {
    state.sosChecked = value == true;
    update(["sos_body", "delete_button"]);
  }
}
